package com.demo.sender.email.handler;

import com.demo.annotation.EmailChannel;
import com.demo.enums.EmailChannelEnum;
import com.demo.sender.email.EmailSenderService;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangfengchen
 */
@Component
public class EmailSenderHandler implements ApplicationContextAware, InitializingBean {

  private ApplicationContext applicationContext;

  private final Map<Integer, Object> emailSenderHandlers = new HashMap<>();

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(EmailChannel.class);
    for (Map.Entry<String, Object> entry : controllers.entrySet()) {
      EmailChannel annotation = AopUtils.getTargetClass(entry.getValue()).getAnnotation(EmailChannel.class);
      EmailChannelEnum channel = annotation.channel();
      emailSenderHandlers.put(channel.getCode(), entry.getValue());
    }
  }

  public EmailSenderService getEmailSenderHandler(Integer channel) {
    if (emailSenderHandlers.containsKey(channel)) {
      return (EmailSenderService) emailSenderHandlers.get(channel);
    }
    throw new RuntimeException("channel not support");
  }
}
